package com.tmptSource.service.impl;

import com.tmpt.dto.Result;
import com.tmpt.utils.DateTool;
import com.tmpt.service.impl.DataLimitService;
import com.tmpt.utils.MD5Util;
import com.tmpt.utils.StringUtils;
import com.tmpt.utils.Utils;
import com.tmptSource.bean.OwPictureMag;
import com.tmptSource.dto.OwPictureMagDto;
import com.tmptSource.mapper.OwDoorRespInfoMapper;
import com.tmptSource.bean.OwDoorRespInfo;
import com.tmptSource.dto.OwDoorRespInfoDto;
import com.tmptSource.dto.PageDto;
import com.tmptSource.mapper.OwPictureMagMapper;
import com.tmptSource.service.intf.IOwDoorRespInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tmptSource.utils.dozer.MyMapper;
import com.tmptSource.utils.page.MyPageUtils;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.log4j.Logger;

/**
 * Created by wxy on 2016/7/28.
 */
@Service(value="owDoorRespInfoService")
@Transactional(propagation = Propagation.REQUIRED)
public class OwDoorRespInfoService implements IOwDoorRespInfoService {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired private DataLimitService dataLimitService;
    @Autowired private Mapper mapper;
    @Autowired private MyMapper myMapper;
    @Autowired private MyPageUtils myPageUtils;
    @Autowired
    private OwDoorRespInfoMapper owDoorRespInfoMapper;
    @Autowired
    private OwPictureMagMapper owPictureMagMapper;


    @Override
    public Result<OwDoorRespInfoDto> pagination(OwDoorRespInfoDto owDoorRespInfoDto,PageDto pageDto) {
        //分页查询
        Result<OwDoorRespInfoDto> result = myPageUtils.pagination(
                owDoorRespInfoDto,pageDto,
                OwDoorRespInfo.class,
                OwDoorRespInfoDto.class,
                owDoorRespInfoMapper,
                false,null);

        return result;
    }

    /**
    * 分布查询，有数据边界控制功能
    * @param owDoorRespInfoDto
    * @param pageDto
    * @param paramMap
    * @return
    */
    @Override
    public Result<OwDoorRespInfoDto> pagination(OwDoorRespInfoDto owDoorRespInfoDto,PageDto pageDto,Map<String,Object> paramMap) {
        //数据边界控制参数
//        Map<String,Object> paramMap1 = dataLimitService.getLimitParam(paramMap);

        //分页查询
        Result<OwDoorRespInfoDto> result = myPageUtils.pagination(
                owDoorRespInfoDto,pageDto,
                OwDoorRespInfo.class,
                OwDoorRespInfoDto.class,
                owDoorRespInfoMapper,
                paramMap,
//                paramMap1,
                false,null);

        return result;
    }


    @Override
    public Result<OwDoorRespInfoDto> selectAll() {
        Result<OwDoorRespInfoDto> result = new Result();

        //排序
        PageDto pageDto = new PageDto();
        pageDto.setSortColumn("id");
        pageDto.setSortOrder("desc");
        Map<String,Object> mapParam = new HashMap<>();
        mapParam.put("page",pageDto);

        List<OwDoorRespInfo> list = owDoorRespInfoMapper.selectAll(mapParam);
        List<OwDoorRespInfoDto> dtoList = myMapper.map(list, OwDoorRespInfoDto.class);
        result.setResultList(dtoList);

        return result.success();
    }

    @Override
    public Result<OwDoorRespInfoDto> selectById(long id) {
        Result<OwDoorRespInfoDto> result = new Result();

        OwDoorRespInfo owDoorRespInfo = owDoorRespInfoMapper.selectById(id);
        OwDoorRespInfoDto dto = mapper.map(owDoorRespInfo,OwDoorRespInfoDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
     * 根据randomKey值查找出ID
     * @param randomKey
     * @return id
     * 2019-11-10
     * helen
     */
    @Override
    public long selectIdByKey(String randomKey) {

        long id = owDoorRespInfoMapper.selectIdByKey(randomKey);
        return id;
    }

    /**
     * 根据企业名称查询randomKey helen
     * @param entName
     * @return
     */
    @Override
    public long selectIdByEntName(String entName) {
        long id = owDoorRespInfoMapper.selectIdByEntName(entName);
        return id;
    }

    @Override
    public long selectCountByEntName(String entName) {
        long count = owDoorRespInfoMapper.selectCountByEntName(entName);
        return count;
    }

    /**
     * 插入空记录
        返回ID值
    */
    @Override
    public Result<OwDoorRespInfoDto> addData(OwDoorRespInfoDto owDoorRespInfoDto){
        Result<OwDoorRespInfoDto> result = new Result();

        //封闭数据
        OwDoorRespInfo owDoorRespInfo = mapper.map(owDoorRespInfoDto, OwDoorRespInfo.class);
        owDoorRespInfo.setCreatedate(DateTool.getCurTimestamp());
        owDoorRespInfo.setUserId(String.valueOf(owDoorRespInfo.getCreatemanId()));
        String randomKey = this.genRandKeyStr(6);
        owDoorRespInfo.setRandomKey(randomKey);

        //调用mapper
        long i = owDoorRespInfoMapper.insert(owDoorRespInfo);
        if(i==0){
            return result.fault("插入失败");
        }
        //伪删除空记录delete_flag=1
        deleteById(Long.valueOf(owDoorRespInfo.getId()),owDoorRespInfo.getCreateman());

        OwDoorRespInfoDto dto = mapper.map(owDoorRespInfo,OwDoorRespInfoDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
     * 二维码插入值
     返回ID值
     */
    @Override
    public Result<OwDoorRespInfoDto> addDataByQRCode(OwDoorRespInfoDto owDoorRespInfoDto){
        Result<OwDoorRespInfoDto> result = new Result();

        String entName = owDoorRespInfoDto.getEntName();

        //默认没有相同企业名称，直接新增
        long count = 0;

        //判断是否只有广告数据，0=不是，1=是，如果是，就不用判断企业名称了，如果不是，就判断企业名称,默认不是
        String onlyAdv = owDoorRespInfoDto.getOnlyAdv();
        int onlyAdvInt = 0;
        if(!StringUtils.isNull(onlyAdv)) {
            onlyAdvInt = Integer.parseInt(onlyAdv);
        }
        if(onlyAdvInt==0){
            //先判断数据库是否存在相同企业没过程，如果有，返回randomKey直接修改数据，如果没有记录，直接插入数据
            count = owDoorRespInfoMapper.selectCountByEntName(entName);
        }

        //封闭数据
        OwDoorRespInfo owDoorRespInfo = mapper.map(owDoorRespInfoDto, OwDoorRespInfo.class);


        //数量为0，表示没有记录，直接新建
        if(count==0){

            //生成新的随机码
            String randomKey = this.genRandKeyStr(6);
            owDoorRespInfo.setRandomKey(randomKey);
            owDoorRespInfo.setCreatedate(DateTool.getCurTimestamp());
            owDoorRespInfo.setCreatemanId(0);
            owDoorRespInfo.setCompanyId(0);
            owDoorRespInfo.setCreateman("0");
            //调用mapper
            long i = this.owDoorRespInfoMapper.insert(owDoorRespInfo);
            if(i==0){
                return result.fault("插入失败");
            }

            //插入多张图片
            if(owDoorRespInfoDto!=null && owDoorRespInfoDto.getOwPictureMagDtoList()!=null) {
                dealPicture(owDoorRespInfoDto, owDoorRespInfo);
            }
        }else{
            //有记录则修改记录
            long id = owDoorRespInfoMapper.selectIdByEntName(entName);
            owDoorRespInfo.setId(id);
            owDoorRespInfo.setModifydate(DateTool.getCurTimestamp());
            owDoorRespInfo.setModifyman("0");
            //调用mapper
            long i = owDoorRespInfoMapper.updateById(owDoorRespInfo);
            if(i==0){
                return result.fault("编辑数据失败");
            }

            //插入多张图片
            if(owDoorRespInfoDto!=null && owDoorRespInfoDto.getOwPictureMagDtoList()!=null) {
                //有新图片时，把老图片删除了；没有新图片的话，先别删除
                if(owDoorRespInfoDto.getOwPictureMagDtoList().size()>0){
                    List<OwPictureMag> owPictureMagList = owPictureMagMapper.selectPictureByOwDoorRespInfoId(owDoorRespInfo.getId());
                    Map<String,Object> delMap = new HashMap<>();
                    delMap.put("modifyman","system");
                    delMap.put("modifydate",DateTool.getCurTimestamp());
                    for(OwPictureMag owPictureMag : owPictureMagList) {
                        delMap.put("id",owPictureMag.getId());
                        owPictureMagMapper.deleteById(delMap);
                    }
                }
                dealPicture(owDoorRespInfoDto, owDoorRespInfo);
            }
        }

        OwDoorRespInfoDto dto = mapper.map(owDoorRespInfo,OwDoorRespInfoDto.class);
        result.setResultObj(dto);
        return result.success();
    }

    private void dealPicture(OwDoorRespInfoDto owDoorRespInfoDto, OwDoorRespInfo owDoorRespInfo) {
        for (OwPictureMagDto owPictureMagDto : owDoorRespInfoDto.getOwPictureMagDtoList()) {
            OwPictureMag owPictureMag = mapper.map(owPictureMagDto, OwPictureMag.class);
            //1:front, 2:back （默认设1），3:店招店牌 4:户外广告
            owPictureMag.setFrontBackSort(
                    StringUtils.isNull(owPictureMagDto.getFrontBackSort()) ? 1 : Integer.parseInt(owPictureMagDto.getFrontBackSort()));
            owPictureMag.setOwTableType("ow_door_resp_info_id");
            owPictureMag.setOwTableId(owDoorRespInfo.getId());
            owPictureMag.setCompanyId(0);
            owPictureMag.setCreatemanId(0);
            owPictureMag.setModifymanId(0);
            owPictureMag.setCreatedate(DateTool.getCurTimestamp());
            owPictureMagMapper.insert(owPictureMag);
        }
    }

    /**
     *
     * @param count
     * @return
     */
    private String genRandKeyStr(int count){
        Random random = new Random();
        String dataSourceStr = "0123456789";
        String sRand="";

        for (int i=0;i<count;i++){
            int index = random.nextInt(dataSourceStr.length());
            char dataChar = dataSourceStr.charAt(index);
            String rand = String.valueOf(dataChar);
            sRand+=rand;
        }
        //获取当前时间年月日时分秒毫秒
        Date date = new Date();
        SimpleDateFormat sim=new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStr = sim.format(date);

        return timeStr+sRand;
    }


    /**
        返回ID值
    */
    @Override
    public Result<OwDoorRespInfoDto> editData(OwDoorRespInfoDto owDoorRespInfoDto){
        Result<OwDoorRespInfoDto> result = new Result();

        String entName = owDoorRespInfoDto.getEntName();
        String randomKey = owDoorRespInfoDto.getRandomKey();
        Map<String,Object> mapParameter = new HashMap();
        mapParameter.put("entName",entName);
        mapParameter.put("randomKey",randomKey);
        //先判断数据库是否存在相同企业没过程，如果有，直接返回提醒用户企业名称重复了
        long count = owDoorRespInfoMapper.selectCountByEntNameExcludeRandomKey(mapParameter);

        if(count==0){
            //封装数据
            OwDoorRespInfo owDoorRespInfo = mapper.map(owDoorRespInfoDto, OwDoorRespInfo.class);
            owDoorRespInfo.setModifydate(DateTool.getCurTimestamp());

            //调用mapper
            long i = owDoorRespInfoMapper.updateById(owDoorRespInfo);
            if(i==0){
                return result.fault("编辑数据失败");
            }
            //插入多张图片
            if(owDoorRespInfoDto!=null && owDoorRespInfoDto.getOwPictureMagDtoList()!=null) {
                //有新图片时，把老图片删除了；没有新图片的话，先别删除
                if(owDoorRespInfoDto.getOwPictureMagDtoList().size()>0){
                    List<OwPictureMag> owPictureMagList = owPictureMagMapper.selectPictureByOwDoorRespInfoId(owDoorRespInfo.getId());
                    Map<String,Object> delMap = new HashMap<>();
                    delMap.put("modifyman","system");
                    delMap.put("modifydate",DateTool.getCurTimestamp());
                    for(OwPictureMag owPictureMag : owPictureMagList) {
                        delMap.put("id",owPictureMag.getId());
                        owPictureMagMapper.deleteById(delMap);
                    }
                }
                dealPicture(owDoorRespInfoDto, owDoorRespInfo);
            }
            OwDoorRespInfoDto dto = mapper.map(owDoorRespInfo,OwDoorRespInfoDto.class);
            result.setResultObj(dto);
        }else{
            result.fault("该企业名称已经存在！请核实后再编辑!");
        }
        return result;
    }

    /**
    伪删除记录，返回ID值
    */
    @Override
    public Result deleteById(long id,String adminMan){
        Result result = new Result();

        Map<String,Object> mapParameter = new HashMap();
        mapParameter.put("id",id);
        mapParameter.put("modifyman",adminMan);
        mapParameter.put("modifydate",DateTool.getCurTimestamp());

        //调用mapper
        long i = owDoorRespInfoMapper.deleteById(mapParameter);
        if(i==0){
            return result.fault("删除数据失败");
        }

        return result.success();
    }





}
